<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="list">

              <el-table-column label="序号" width="120" type="index" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button size="small" type="success" @click="assignPerm(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(scope.row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>

            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="page.total"
                :page-size="page.pagesize"
                @current-change="currentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-card>
      <!-- 弹窗占位 -->
      <el-dialog :title="roleForm.id?'编辑角色':'新增角色'" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <!-- data 是树形数据
        props 指定渲染的字段
        default-expand-all 默认展开送哦有
        show-checkbox 是显示多选框
        check-strictly 父子节点间独立选择
        -->

        <!--
        树形没有 v-model
        这里的取值和设置值需要
        一个属性和两个函数的配合
        node-key 指定指定每个节点对象用来标记的 key
        然后可以通过 setCheckedKeys 设定被选中的值
        getCheckedKeys 获取用户最新的选择
        -->
        <el-tree
          ref="permTree"
          :data="permissionList"
          :props="{label: 'name'}"

          :default-expand-all="true"
          :show-checkbox="true"

          :check-strictly="true"
          node-key="id"
        />

        <template #footer>
          <el-row type="flex" justify="center">
            <el-button type="primary" @click="btnPermOK">确认</el-button>
            <el-button @click="btnPermCancel">取消</el-button>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getCompanyInfo,
  getRoleList,
  deleteRole,
  getRoleDetail,
  updateRole,
  addRole,
  assignPerm
} from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { listToTreeData } from '@/utils'
export default {
  data() {
    return {
      formData: {},
      list: [],
      page: {
        page: 1,
        pagesize: 2,
        total: 0
      },

      // 新增/编辑弹窗数据
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { max: 10, message: '长度在 10 字符以内' }
        ],
        description: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { max: 50, message: '长度在 50 字符以内' }
        ]
      },

      showPermDialog: false,
      permissionList: [],
      roleId: ''
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
  },
  methods: {
    async assignPerm(id) {
      // 获取全部权限数据, 树形处理
      const res = await getPermissionList()
      const permActive = res.filter(item => item.enVisible === '1')
      this.permissionList = listToTreeData(permActive, '0')
      console.log(this.permissionList)

      // 那角色的详情
      // 在弹窗出现以后, 根据当前被点击的角色已有权限
      // 选中旧数据
      const { permIds } = await getRoleDetail(id)
      // 因为我们已经将 ID 设置为属性的节点标记
      // 可以通过执行 setCheckedKeys 设定哪些节点被选中
      // 只需传入数组即可
      // 弹出弹窗
      this.showPermDialog = true

      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(permIds)
        console.log(permIds)
      })

      this.roleId = id
    },
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.$store.state.user.userInfo.companyId)
    },
    async getRoleList() {
      const res = await getRoleList(this.page)
      console.log(res)
      this.list = res.rows
      this.page.total = res.total
    },
    currentChange(newPage) {
      // 这是翻页触发的函数, 饿了么会传入当前最新选中的页码
      // 1. 改页码
      this.page.page = newPage
      // 2. 重新发请求
      this.getRoleList()
    },
    async delRole(id) {
      try {
        console.log('删除')
        // 1. 二次校验
        await this.$confirm('是否确认删除?')
        // 2. 发请求
        await deleteRole(id)
        // 3. 提示用户
        this.$message.success('删除成功')
        // 4. 更新页面
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    async editRole(id) {
      // 回显数据
      this.roleForm = await getRoleDetail(id)
      // 弹出弹窗
      this.showDialog = true
    },
    async btnOK() {
      try {
        // 1. 校验
        await this.$refs.roleForm.validate()
        // 2. 请求
        if (this.roleForm.id) {
          // 编辑
          await updateRole(this.roleForm)
        } else {
          // 新增
          await addRole(this.roleForm)
        }
        // 3. 提示
        this.$message.success('操作成功')
        // 4. 关闭弹窗
        this.showDialog = false
        // 5. 更新数据
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    btnCancel() {
      // 1. 清理表单
      this.roleForm = {
        name: '',
        description: ''
      }
      // 2. 清理报错
      this.$refs.roleForm.resetFields()
      // 3. 关闭弹窗
      this.showDialog = false
    },

    async btnPermOK() {
      // 发请求
      // 需要两个数据1被点击的角色id 2当前选中的权限id数组
      await assignPerm({
        id: this.roleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      // 提示用户
      this.$message.success('修改成功')
      // 关闭弹窗
      this.showPermDialog = false
    },
    btnPermCancel() {
      // 清理数据 没有 v-model 只能用树形的 setCheckedKeys 实现
      this.$refs.permTree.setCheckedKeys([])
      // 关闭弹窗
      this.showPermDialog = false
    }
  }
}
</script>

<style>

</style>
